<template>
  <div class="box">
    <!-- 查询项目 -->
    <!-- <headerSearch :selectObj="selectObject" :goSearchFc="searchClick" /> -->
    <!-- 信息列表 -->
    <BaseTable :data="messageData" :columns="messageDataColumns" :tableHeight="tableHeight" :pagination="false" :loading="loading"></BaseTable>

    <!-- 分页区域 -->
    <div class="page">
      <el-pagination background @size-change="handleSizeChange" :total="queryAll.total" :current-page="queryAll.startpage" :page-sizes="[ 15, 20, 25, 30, 35]" :page-size="queryAll.pagesize" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    </div>
    <!-- 新增/编辑人员关联记录 -->
    <el-drawer :title="addEditSonFlag?'新增消息人员关联记录':'修改消息人员关联记录'" :before-close="handleClose" :visible.sync="addEditSonDrawer" direction="rtl" size:="30%">
      <div class="demo-drawer__content" style="padding: 20px;">
        <el-form :model="userForm" ref="formRef" :rules="formRules">
          <el-form-item label="选择用户：" :label-width="formLabelWidth" prop="accNo">
            <el-select v-model="userForm.accNo" clearable filterable remote :remote-method="userNameRemote">
              <el-option v-for="(item,index) in userSelectData" :key="index" :label="item.userName" :value="item.accNo"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button size="small" type="primary" @click="saveson" :loading="sonLoading">{{ sonLoading ? '提交中 ...' : '保 存' }}</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 关联用户 -->
    <el-drawer class="yesgoods" title="关联用户"  :visible.sync="drawerthree" size="70%" :before-close="handleClose1">
      <div style="padding:0 10px">
        <div class="search">
          <div class="search_input">
            <el-select v-model="checkUserName" clearable filterable remote :remote-method="userNameRemote" placeholder="用户名称" style="margin-right:10px;">
              <el-option v-for="(item,index) in userSelectData" :key="index" :label="item.userName" :value="item.userName"></el-option>
            </el-select>
            <el-button type="primary" @click="getSonDataList('check')">查询</el-button>
          </div>
          <div class="anniu">
            <el-button plain icon="el-icon-plus" size="mini" @click="createson" v-if="menuArr.includes('消息提醒关联用户新增')"></el-button>
          </div>
        </div>
        <BaseTable :data="tableSonData" :columns="tableSonDataColumns" :tableHeight="tableHeight+30" :pagination="false"></BaseTable>
        <div class="page">
          <el-pagination background @size-change="handleSonSizeChange" :total="children.totalNum" :current-page="children.currentPage" :page-size="children.pagesize" @current-change="handleSonCurrentChange" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import { isObjectValueEqual } from '@/libs/date'
import BaseTable from '@/components/BaseTable'
import headerSearch from './component/headerSearch'
export default {
  name: 'metadataOperationprocess',
  components: {
    BaseTable,
    headerSearch
  },
  data() {
    return {
      userForm: {
        accNo: '',//用户名称编号,
        id: '',//主键id
      },
      checkUserName: '',//子列表查找的名字
      userSelectData: [],//用户下拉选中框
      messagetypevalue: '',//消息种类编码
      messageTypeLabel: '',//消息种类名称
      sonLoading: false,
      // 搜索框显示对象
      selectObject: [
        {
          name: "过程名称",
          type: "input",
          modelName: "oprocessName"
        }
      ],
      //首页的colums
      messageDataColumns: [
        {
          prop: 'dictValue',
          label: '消息种类编码'
        },
        {
          prop: 'dictLabel',
          label: '消息种类名称'
        },

        {
          label: '操作',
          align: 'center',
          width: 220,
          render: (h, params) => {
            return h(
              'div', {
              class: 'btnClass'
            },
              [

                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: params.row.delFlag == '1'
                  },
                  domProps: {
                    innerHTML: `<span style='color:#9420A8;display: ${this.menuArr.includes('消息提醒列表按钮')?"block":"none"}'><i class='iconfont icon-1-09'></i><span  style='padding-left:5px;'>列表</span></span>`
                  },
                  on: {
                    click: () => {
                      click: this.handleList(params.row)
                    }
                  }
                }),

              ]
            )
          }
        }
      ],
      //子列表的colums
      tableSonDataColumns: [
        {
          prop: 'accNo',
          label: '账号'
        },
        {
          prop: 'userName',
          label: '用户名称'
        },
        {
          prop: 'createName',
          label: '创建人'
        },
        {
          prop: 'createTime',
          label: '创建时间'
        },
        {
          prop: 'updateName',
          label: '更新人'
        },
        {
          prop: 'updateTime',
          label: '更新时间'
        },
        {
          label: '操作',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return h(
              'div', {
              class: 'btnClass'
            },
              [
                // h('el-button', {
                //   props: {
                //     size: 'mini',
                //     disabled: params.row.delFlag == '1'
                //   },
                //   style: {
                //     marginRight: '10px'
                //   },
                //   domProps: {
                //     innerHTML: `<span style='color:#0B6CD6'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
                //   },
                //   on: {
                //     click: () => {
                //       click: this.handleupdate(params.row.id)
                //     }
                //   }
                // }),
                h('el-button', {
                  props: {
                    size: 'mini',
                    // disabled:params.row.delFlag=='1'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    innerHTML: `<span style='color:#F75E5E;display: ${this.menuArr.includes('消息提醒关联用户删除')?"block":"none"}'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      click: this.handleDelete(params.row.id)
                    }
                  }
                }),
              ]
            )
          }
        }
      ],
      menuArr:[],
      //首页数据
      messageData: [],
      //子列表数据
      tableSonData: [],
      addEditSonFlag: true,
      addEditSonDrawer: false,
      loading: false,
      flagHint: false,

      // 校验规则
      formRules: {
        accNo: [{
          required: true,
          message: '请选择用户',
        }],
      },

      drawerthree: false,//打开子列表
      formLabelWidth: '130px',
      //子列表
      children: {
        totalNum: 0,
        currentPage: 1,
        pagesize: 10
      },

      // 首页
      queryAll: {
        startpage: 1,
        pagesize: 15,
        total: 0,
      },


    }
  },
  async activated() {
    var menuArr = []
    var menuId = ""
    if(localStorage.getItem("menuArr")){
      menuArr = JSON.parse(localStorage.getItem("menuArr"))
    }
    menuArr.map(item=>{
      item.children.map(v=>{
        if(window.location.href.includes(v.url)){
          menuId = v.id
        }
      })
    })

    if(menuId){
      this.menuArr = []
      await this.$http.get(`/${this.$ServiceName}/api/external/sysmenubtn/listresourcebtnbyid?menuId=${menuId}`,{ timeout: 30000,})
              .then(res => {
                res.data.data.map(item=>{
                  this.menuArr.push(item.resourceName)
                })

              }).catch((error)=>{})
    }
    if (this.$store.state.app.searchResouce == "menu") {
      this.queryAll = {
        startpage: 1,
        pagesize: 15,
        total: 0,
      }
      this.getDataList() // 获取作业过程数据
    }

  },
  watch: {

    userForm: {
      handler(newVal, oldVal) {
        this.flagHint = isObjectValueEqual(newVal, oldVal)
      },
      deep: true
    }
  },
  computed: {
    tableHeight: function () {
      return this.$store.state.tableHeight + 30
    }
  },
  methods: {
    //用户下拉框远程搜索
    userNameRemote(query) {
      this.getUserSelectData(query, '')
    },
    //获取用户下拉选中框
    getUserSelectData(keyword = '', accNo = '') {
      //初始化下拉表数组
      this.userSelectData = []
      this.$http.get(
        `/${this.$ServiceName}/api/external/public/listuser`, {
        params: {
          keyword: keyword,
          accno: accNo
        }
      }
      ).then(res => {
        if (res.data.success) {
          this.userSelectData = res.data.data
          accNo ? this.userForm.accNo = accNo : ''//accNo存在就是编辑模式开始时的初始化赋值
        }
      })
    },
    //子列表的编辑
    handleupdate(id) {
      let that = this
      that.userForm.id = id //储存主键id以备调用
      that.userForm.accNo = ''//清空accno
      //获取用户详细信息
      that.$http.get(
        `/${this.$ServiceName}/api/external/mmessageperson/${that.$version}/getmessageuser`, {
        params: {
          id: id
        }
      }
      ).then(res => {
        if (res.data.success) {
          that.getUserSelectData('', res.data.data.accNo)
          that.addEditSonFlag = false
          that.addEditSonDrawer = true
        }
      })
    },

    cellStyle() {
      return 'border-left: nthis.oppTypesone;border-right: none;'
    },

    //新增子过程
    createson(index, row) {
      //清空数据
      this.userForm = {
        accNo: "",
        id: '',
      }
      // 获取用户下拉
      this.getUserSelectData()
      this.addEditSonFlag = true
      this.addEditSonDrawer = true
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate()
      })
    },
    //新增/编辑子过程
    saveson() {
      this.$refs['formRef'].validate(async valid => {
        if (valid) {
          this.sonLoading = true
          //找到accno对应的username
          let userName = this.userSelectData.filter(res => res.accNo == this.userForm.accNo)[0].userName
          if (this.addEditSonFlag) {
            await this.$http
              .post(`/${this.$ServiceName}/api/external/mmessageperson/${this.version}/insert`, {
                messageTypeValue: this.messagetypevalue,
                messageTypeLabel: this.messageTypeLabel,
                accNo: this.userForm.accNo,
                userName: userName,
              }).then(res => {
                this.$message.success(res.data.msg)
                this.getSonDataList()
                this.addEditSonDrawer = false
                this.sonLoading = false
              }).catch(error => { this.sonLoading = false })

          } else {
            await this.$http.put(`/${this.$ServiceName}/api/external/mmessageperson/${this.$version}/updatebyid`, {
              id: this.userForm.id,
              accNo: this.userForm.accNo,
              userName: userName,
            }).then(res => {
              this.$message.success(res.data.msg)
              this.getSonDataList()
              this.addEditSonDrawer = false
              this.sonLoading = false
            }).catch(error => { this.sonLoading = false })
          }
        } else {
          return false
        }
      })

    },
    async searchClick(searchData) {
      console.log('search', this.queryAll, searchData)
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData);
      this.getDataList()
    },
    //获取作业过程table数据
    async getDataList() {
      this.loading = true
      await this.$http.get(
        `/${this.$ServiceName}/api/external/mmessageperson/${this.$version}/listall`, {
        params: this.queryAll
      }
      ).then(res => {
        this.loading = false
        if (res.data.success) {
          this.messageData = res.data.data.pages
          this.queryAll.total = res.data.data.totalNum
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
        }
      }).catch(error => { this.loading = false })
    },
    //列表操作
    handleList(row) {
      this.drawerthree = true
      this.messagetypevalue = row.dictValue
      this.messageTypeLabel = row.dictLabel
      //获取子列表数据
      this.getSonDataList()
    },

    async getSonDataList(type) {
      // 获取用户下拉
      this.getUserSelectData()
      let userName = ''
      if (type == 'check') { //等于check就是点击查询按钮
        //找到accno对应的username
        userName = this.checkUserName
        //初始化pagesize
        this.children.currentPage = 1
      }
      await this.$http.get(
        `/${this.$ServiceName}/api/external/mmessageperson/${this.$version}/listmessageuser`, {
        params: {
          messagetypevalue: this.messagetypevalue,
          username: userName,
          pagesize: this.children.pagesize,
          startpage: this.children.currentPage
        }
      }
      ).then(res => {
        if (res.data.success) {
          this.tableSonData = res.data.data.pages
          this.children.totalNum = res.data.data.totalNum
          this.children.currentPage = res.data.data.pageNum
          this.children.pagesize = res.data.data.pageSize
        }
      }).catch(error => { })
    },

    handleDelete(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http
            .delete(
              `/${this.$ServiceName}/api/external/mmessageperson/${this.$version}/deletebyid`, {
              params: {
                id: id
              }
            }
            )
            .then(res => {
              if (res.data.code == '0000') {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.getSonDataList()
              } else {
                this.$message({
                  message: res.data.msg,
                  type: 'warning'
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 每页显示的条数
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getDataList()
    },
    handleSonSizeChange(val) {
      this.children.pagesize = val
      this.getSonDataList()
    },
    handleSonCurrentChange(val) {
      this.children.currentPage = val
      this.getSonDataList()
    },


    // 关闭抽屉操作
    handleClose(done) {
      if (this.flagHint) {
        this.$confirm('您已修改了数据，确定是否关闭？')
          .then(_ => {
            done()
            this.userForm = {
              accNo: '',
              id: ''
            }
          })
          .catch(_ => { })
      } else {
        done()
        this.userForm = {
          accNo: '',
          id: ''
        }
      }

    },
    // 关闭抽屉操作
    handleClose1(done) {
      // this.$confirm('确认关闭？')
      //   .then(_ => {
          done()
        // })
        // .catch(_ => { })
      this.userForm = {
        accNo: '',
        id: ''
      }
    },

  }
}
</script>

<style lang="less" scoped>

.yesgoods /deep/ .el-drawer__body {
  padding-top: 0;
  margin-top: 0 !important;
  background: #f5f7fa;
}
.search {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .anniu {
    padding: 10px 20px 10px;
  }
}
.yesgoods .anniu,
/deep/ .el-drawer__body {
  margin-top: 0 !important;
}

/deep/ .el-drawer__header {
  // margin-bottom: 12px;
  height: 40px;
  line-height: 41px;
  padding: 0 16px;
  box-sizing: border-box;
  border-bottom: 1px solid gainsboro;
  margin-bottom: 0;
}

/deep/ .el-drawer__open .el-drawer.rtl {
  background: #f5f7fa;
}

.page {
  padding: 10px;
  background: #ffffff;
  border-radius: 4px 4px 0 0;
}

.box {
  background: #ffffff;
  //   border: 1px solid #e1e4eb;
  border-radius: 4px 4px 0 0;
}

.title {
  background: #f5f7fa;
  height: 40px;
  line-height: 40px;

  p {
    font-family: MicrosoftYaHei;
    font-size: 16px;
    color: #303133;
    letter-spacing: 0;
    line-height: 16px;
    padding-left: 14px;
    line-height: 40px;
  }
}

/deep/ .el-table .cell {
  white-space: nowrap;
}

/deep/ .el-form-item--mini .el-form-item__label {
  line-height: 0;
}

/deep/ .el-pagination {
  text-align: right;
}

/deep/ .el-table th > .cell {
  font-family: PingFangSC-Semibold;
  font-size: 14px;
  color: #606266;
}

/deep/ .el-table .el-button:focus,
.el-button:hover {
  background-color: #fff;
  color: #338ce8;
  border: 1px solid #e1e4eb;
}

/deep/ .el-table .el-button--mini {
  color: #1684f6;
  border-color: transparent;
  background: transparent;
}

/deep/ .el-table th {
  border-left: 1px solid #ebeef5;
}

/deep/ .el-table th:nth-child(1) {
  border-left: none;
}

/deep/ .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #f5f7fa;
}

/deep/.el-pagination.is-background .btn-next,
/deep/ .el-pagination.is-background .btn-prev,
/deep/ .el-pagination.is-background .el-pager li {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-radius: 3px;
  border-radius: 3px;
}

.box {
  overflow: hidden;
}

.selectBox {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-bottom: 0;
  border-left: none;
  height: 50px;
  position: relative;
  display: flex;
  align-items: center;
  padding-left: 16px;
}

.el-button {
  margin-left: 0px !important;
}

.relatedInstitutions /deep/ .el-drawer__open .el-drawer.rtl {
  width: 30% !important;
  background: #f5f7fa;
}

.headerspan {
  background: #ffffff;
  border-bottom: 1px solid #e1e4eb;
  line-height: 40px;
  padding-left: 1rem;
}

.headerspan-item {
  line-height: 40px;
  padding-left: 1rem;
  font-size: 14px;
  color: #606266;
  letter-spacing: 0;
}

.btn /deep/ .el-button--mini,
.el-button--mini.is-round {
  padding: 7px 6px;
}
</style>
